package com.msb.mall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.msb.common.exception.BizErrorCodeEnum;
import com.msb.common.utils.PageUtils;
import com.msb.common.vo.CommonPageReq;
import com.msb.common.vo.CommonResult;
import com.msb.mall.core.dao.product.BrandDao;
import com.msb.mall.core.dao.product.CategoryBrandRelationDao;
import com.msb.mall.core.entity.product.BrandEntity;
import com.msb.mall.core.entity.product.CategoryBrandRelationEntity;
import com.msb.mall.product.service.BrandService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service("brandService")
@Slf4j
public class BrandServiceImpl extends ServiceImpl<BrandDao, BrandEntity> implements BrandService {

    @Autowired
    private BrandDao brandDao;
    @Autowired
    private CategoryBrandRelationDao categoryBrandRelationDao;

    @Override
    public PageUtils queryPage(CommonPageReq<Map<String, Object>> req) {
//        IPage<BrandEntity> page = this.page(
//                new Query<BrandEntity>().getPage(params),
//                new QueryWrapper<BrandEntity>()
//        );

        Map<String, Object> reqMap = req.getData();
        String name = (String) reqMap.get("name");

        IPage<BrandEntity> page = new Page<>(req.getCurrPage(), req.getPageSize());
        LambdaQueryWrapper<BrandEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.isNotEmpty(name), BrandEntity::getName, name);

        IPage<BrandEntity> iPageResult = baseMapper.selectPage(page, queryWrapper);
        return new PageUtils(iPageResult);
    }

    @Override
    public IPage<BrandEntity> findAll(Map<String, Object> params) {
        IPage<BrandEntity> page = new Page<>(1, 10);
        return brandDao.selectPage(page, new LambdaQueryWrapper<>());
    }

    @Override
    public CommonResult saveSingle(BrandEntity brand) {
        CommonResult commonResult = CommonResult.success();

        // 品牌名称不能重复
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("name", brand.getName());
        List<BrandEntity> oldList = brandDao.getBrandByCondition(paramMap);
        if (!CollectionUtils.isEmpty(oldList)) {
            commonResult.setCode(BizErrorCodeEnum.VALID_EXCEPTION.getCode());
            commonResult.setMsg("品牌名称不能重复！");
            return commonResult;
        }

        baseMapper.insert(brand);
        return commonResult;
    }

    @Transactional
    @Override
    public CommonResult updateSingle(BrandEntity brand) {
        CommonResult commonResult = CommonResult.success();

        // 品牌名称不能重复
        if(StringUtils.isNotEmpty(brand.getName())) {
            Map<String, Object> paramMap = new HashMap<>();
            paramMap.put("name", brand.getName());
            List<BrandEntity> oldList = brandDao.getBrandByCondition(paramMap);
            if (!CollectionUtils.isEmpty(oldList)) {
                if (!oldList.get(0).getBrandId().equals(brand.getBrandId())) {
                    commonResult.setCode(BizErrorCodeEnum.VALID_EXCEPTION.getCode());
                    commonResult.setMsg("品牌名称不能重复！");
                    return commonResult;
                }
            }
        }

        baseMapper.updateById(brand);

        return commonResult;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteBrand(List<Long> brandIds) {
        // 如果存在 品牌分类关联，则先删除
        LambdaQueryWrapper<CategoryBrandRelationEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(CategoryBrandRelationEntity::getBrandId, brandIds);
        Integer count = categoryBrandRelationDao.selectCount(queryWrapper);
        if (count != null && count > 0) {
            // 执行删除
            categoryBrandRelationDao.delete(queryWrapper);
        } else {
            log.info("待删除的品牌ID未关联商品分类！");
        }

//        categoryBrandRelationDao.delete(queryWrapper); // 或直接执行删除

        // 批量删除品牌id
        baseMapper.deleteBatchIds(brandIds);
    }

}
